package com.hiv.utils;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.hiv.common.WebResponse;
import com.hiv.common.domain.weixin.WeChatSession;
import com.hiv.common.enums.ErrorCode;
import com.hiv.common.utils.AssertUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.Objects;

/**
 * @author zhanghong
 * @version BucUserUtils.java, v 0.1 2022/3/19 21:44 下午 BucUserUtils Exp $$
 */
@Slf4j
public class WXUtils {

    private static final String GET_PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s";

    /**
     * 获取openid信息
     */
    private static final String GET_OPEN_ID_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";

    /**
     * 获取accessToken信息
     */
    private static final String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";

    /**
     * 获取 openId
     * @return
     */
    public static WebResponse<WeChatSession> getOpenId(String js_code, String appId, String secret) {
        //微信的接口
        String url = String.format(GET_OPEN_ID_URL, appId, secret, js_code);
        try {
            RestTemplate restTemplate = new RestTemplate();
            //进行网络请求,访问url接口
            ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
            log.info("WXUtils.getOpenId 微信授权登录 response {}", JSON.toJSONString(responseEntity));
            //根据返回值进行后续操作
            if (responseEntity != null && responseEntity.getStatusCode() == HttpStatus.OK) {
                String sessionData = responseEntity.getBody();
                Gson gson = new Gson();
                //解析从微信服务器获得的openid和session_key;
                WeChatSession weChatSession = gson.fromJson(sessionData, WeChatSession.class);
                if (StringUtils.isNotBlank(weChatSession.getErrcode())) {
                    return WebResponse.build(ErrorCode.WECHAT_AUTH_LOGIN_FAIL.getCode(), weChatSession.getErrmsg());
                }
                return WebResponse.build(weChatSession);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return WebResponse.build(ErrorCode.WECHAT_AUTH_LOGIN_FAIL);
    }

    /**
     * 获取access token
     * @param appId
     * @param secret
     * @return
     */
    public static WebResponse<String> getAccessToken(String appId, String secret) {
        String getAccessTokenUrl = String.format(GET_ACCESS_TOKEN_URL, appId, secret);
        String response = HttpUtil.get(getAccessTokenUrl);
        log.info("WXUtils.getAccessToken 获取accessToken response {}", response);
        Map<String, String> map = JSON.parseObject(response, Map.class);
        if (map.containsKey("access_token")) {
            // 请求成功
            String access_token = map.get("access_token");
            return WebResponse.build(access_token);
        }

        log.error("WXUtils.getAccessToken 获取accessToken失败 error {}", map.get("errmsg"));
        AssertUtil.assertTrue(false, ErrorCode.PARAM_ERROR, "获取accessToken失败");
        return null;
    }


    /**
     * 获取手机号
     * @param code
     * @param appId
     * @param secret
     * @return
     */
    public static WebResponse<String> getPhone(String code, String appId, String secret) {
        WebResponse<String> accessToken = getAccessToken(appId, secret);
        if (StringUtils.isNotBlank(accessToken.getData())) {
            String getPhoneUrl = String.format(GET_PHONE_URL, accessToken.getData());
            JSONObject json = new JSONObject();
            json.put("code", code);
            String post = HttpUtil.createPost(getPhoneUrl).body(json.toString()).execute().body();
            log.info("WXUtils.getPhone 获取手机号 response {}", post);
            JSONObject jsonObject = JSON.parseObject(post);
            if (jsonObject.containsKey("errcode") && Objects.equals(jsonObject.get("errcode"), 0)) {
                String phone_info = jsonObject.getString("phone_info");
                if (StringUtils.isNotBlank(phone_info)) {
                    JSONObject jsonObject1 = JSON.parseObject(phone_info);
                    if (jsonObject1.containsKey("phoneNumber")) {
                        return WebResponse.build(jsonObject1.getString("phoneNumber"));
                    }
                }
            }
        }
        log.error("WXUtils.getPhone 获取手机号失败");
        AssertUtil.assertTrue(false, ErrorCode.PARAM_ERROR, "获取手机号失败");
        return null;
    }
}
